

package com.sanyang.lawyer.utils;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Component
public class FastDFSutils {

    //nginx 的 访问ip
    @Value("${fdfs.reqHost}")
    private String reqHost;

    //nginx的访问端口
    @Value("${fdfs.reqPort}")
    private String reqPort;

    //得到操作客户端
    @Autowired
    private FastFileStorageClient storageClient;


    //上传文件
    public String uploadfile(MultipartFile file) throws Exception{
        StorePath storePath = null;
        try{
            storePath = storageClient.uploadFile((InputStream)file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        }catch (Exception e) {
            throw new Exception();
        }
        String url = getSuccessURL(storePath.getFullPath());
        return url;
    }

    //将上传返回的path对象转换为真实的访问地址
    public String getSuccessURL(String path){
        return "http://"+reqHost+":"+reqPort+"/"+path;
    }

    //根据文件在服务器上的地址删除文件对象
    public void delete_path(String path) throws Exception{
        storageClient.deleteFile(path);
    }

    //下载文件
    public byte[] downloadfile(String filepath){
        String fileURL = filepath.substring(filepath.indexOf("8888/"));
        fileURL = fileURL.substring(fileURL.indexOf("/") + 1);

        String group = fileURL.substring(0, fileURL.indexOf("/"));
        String path = fileURL.substring(fileURL.indexOf("/") + 1);

        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = storageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }

    //删除文件
    public String deletefile(String filepath){
        storageClient.deleteFile(filepath);
        return "1";
    }








}
